package bbs.web.newservlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import bbs.bean.Result;

public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取地址中的方法名   ？
		String  path = request.getRequestURL().toString();
		path= path.replaceAll(".+?/(\\w*)\\.s$","$1");//贪婪模式  ？
		
		// post 请求要设置字符集
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//通过反射查找对应方法给前端服务，this.getClass() 获取当前对象的类对象
		try {
			Method m = this.getClass().getDeclaredMethod(
					path, 
					HttpServletRequest.class, HttpServletResponse.class);
			//执行方法
			System.out.println("执行:" + m);
			m.invoke(this, request,response);
		} catch (NoSuchMethodException  | SecurityException
				| IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			throw new RuntimeException("方法名错误："+path,e);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	public static void toJson(HttpServletResponse response,Object obj) throws IOException{
		String s = new Gson().toJson(obj);
		response.getWriter().append(s);
	}
}
